import { onBeforeUnmount, onMounted, ref } from 'vue'
import { browserChannel, randomWord } from '@/utils/utils'
import { systemMessage } from '@/base/systemMessage/systemMessageInstance'
import { useDeskAppStore } from '@/stores/systemApp/deskApp'
import { useSystemSettingStore } from '@/stores/desk/systemSetting'
import { useRunningTasksStore } from '@/stores/taskBar/runningTasks'
import { BrowserChannelType } from '@/hooks/browserHooks'
import type { DeskAppComponent, IDestApp } from '@/stores/systemApp/deskApp'
import type { IRunningTasksList } from '@/stores/taskBar/runningTasks'
import type { Ref } from 'vue'

/** 判断新建的文件窗口是否会和之前的重合
 * @param {IRunningTasksList[]} list
 * @param {Number} x
 * @param {Number} y
 */
const isOverlapping = (
  list: IRunningTasksList[],
  x: number,
  y: number
): {
  x: number
  y: number
} => {
  const overlapping = list.find((item) => item.x == x && item.y === y)
  if (overlapping) {
    x += 32
    y += 32
    if (x + overlapping.width > innerWidth) x = 0
    if (y + overlapping.height > innerHeight - 40) y = 0
    return isOverlapping(list, x, y)
  } else {
    return { x, y }
  }
}

interface IUseSystemHotkeyHookReturn {
  systemProjectionVisible: Ref<boolean>
}

// 系统快捷键
export const useSystemHotkeyHook = (): IUseSystemHotkeyHookReturn => {
  const { handleCreateTask } = useCreateTask()
  const systemSettingStore = useSystemSettingStore()

  const systemProjectionVisible = ref<boolean>(false)

  const handleKeydown = async (ev: KeyboardEvent) => {
    const key = ev.key.toLowerCase()
    if (ev.altKey) {
      ev.preventDefault()
      ev.stopPropagation()
      // 打开文件夹
      if (key === 'e') handleCreateTask('folder')
      // 锁屏
      if (key === 'l') systemSettingStore.setDeskLock(true)
      // 多屏投影
      if (key === 'p') {
        systemProjectionVisible.value = !systemProjectionVisible.value
      }
    }
  }

  const handleKeyup = (ev: KeyboardEvent) => {
    const key = ev.key.toLowerCase()
    if (ev.altKey) {
      if (key === 'e') {
        ev.preventDefault()
        ev.stopPropagation()
      }
    }
  }

  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleKeydown)
    window.removeEventListener('keyup', handleKeyup)
    window.removeEventListener('keypress', handleKeyup)
  })

  onMounted(() => {
    window.addEventListener('keydown', handleKeydown)
    window.addEventListener('keyup', handleKeyup)
    window.addEventListener('keypress', handleKeyup)
  })

  return {
    systemProjectionVisible
  }
}

interface IUseCreateTaskReturn {
  handleCreateTask: (taskName: DeskAppComponent, icon?: string) => { appId: string; taskId: string } | undefined
}

// 创建新任务
export const useCreateTask = (): IUseCreateTaskReturn => {
  const runningTasksStore = useRunningTasksStore()
  const deskAppStore = useDeskAppStore()

  // 通过 appId 获取任务的数据 通过数据创建任务
  const getDeskAppList = (taskName: DeskAppComponent, icon?: string): IDestApp | undefined => {
    const { deskAppList, systemAppList } = deskAppStore.$state
    return [...deskAppList, ...systemAppList].find((item) => {
      if (icon) return item.appId === taskName && item.icon === icon
      return item.appId === taskName
    })
  }

  // 创建任务
  const handleCreateTask = (
    taskName: DeskAppComponent,
    icon?: string
  ): { appId: string; taskId: string } | undefined => {
    const data = getDeskAppList(taskName, icon)
    if (!data?.prod) {
      systemMessage.warning(`${taskName}正在开发中...`)
      return
    }
    if (!data) return
    const find = runningTasksStore.$state.runningTasks.find((item) => item.appId === data.appId)
    if (data.onlyApp && find) {
      runningTasksStore.checkedCurrentTask(find.appId, find.list[0].id, true)
      return { appId: find.appId, taskId: find.list[0].id }
    }
    let x = data.isCenter ? (innerWidth - data.size.default[0]) / 2 : data?.x || 0
    let y = data.isCenter ? (innerHeight - data.size.default[1]) / 2 : data?.y || 0
    if (find) {
      const { x: X, y: Y } = isOverlapping(find.list, x, y)
      x = X
      y = Y
    }
    const taskId = randomWord(20, `running-task-${data.appId}-`)
    deskAppStore.resetDeskAppKey('isChecked', false)
    runningTasksStore
      .createNewTask({
        appId: data.appId,
        list: [
          {
            tray: data.tray,
            trayIcon: data.trayIcon[0],
            taskBar: data.taskBar,
            isSystemTopBar: data.isSystemTopBar,
            component: data.component,
            isTaskBar: data.isTaskBar,
            isDrag: false,
            isTray: false,
            isMin: false,
            isFull: false,
            isMax: false,
            isChecked: true,
            minSize: [data.size.default[2], data.size.default[3]],
            maxSize: [data.size.default[4], data.size.default[5]],
            isResize: data.isResize,
            id: taskId,
            icon: data.icon,
            title: data.name,
            width: data.size.default[0],
            height: data.size.default[1],
            x,
            y,
            endX: x,
            endY: y,
            componentData: {
              trayMenu: data.trayMenu,
              ...data.componentData
            }
          }
        ]
      })
      .then(() => {
        browserChannel.postMessage({ type: BrowserChannelType.createTask, data: taskName })
      })
    return { appId: data.appId, taskId }
  }

  return {
    handleCreateTask
  }
}
